const moment = require('moment')
const conn = require('../db/db.js')
const marked = require('marked')

const addArticlepage = (req,res)=>{
    if(!req.session.islogin) return res.redirect('/')
    res.render('./article/add.ejs',{
        user:req.session.user,
        islogin:req.session.islogin
    })
}

const addNewArticle = (req,res)=>{
    const body = req.body       
    body.ctime = moment().format('YYYY-MM-DD HH:mm:ss')
    // console.log(body);
    const sql = 'insert into hm_article set ?'
    conn.query(sql,body,(err,result) => {        
        if(err) return res.send({msg:'添加文章失败',status:'501'})
        if(result.affectedRows!==1) return res.send({msg:'添加文章失败',status:'502'})
        res.send({msg:'添加文章成功',status:200,insertId:result.insertId})    
    })
}

//文章渲染到info页面
const showArticle = (req,res) => {
    const id = req.params.id

    
    const sql = 'select * from hm_article where id = ?'
    conn.query(sql,id,(err,result)=>{
        // console.log(result[0].content)
        if(err) return res.send({msg:'展示文章失败',status:'501'})
        if(result.length !=1) return  res.redirect('/')
        const html = marked(result[0].content)        
        result[0].content = html
        res.render('./article/info.ejs',{
            user:req.session.user,
            islogin:req.session.islogin,
            article:result[0]
        })
    })
    
}

//文章编辑页面
const editArticlePage = (req,res) =>{
    const id = req.params.id
    
    const sql = 'select * from hm_article where id=?'
    conn.query(sql,id,(err,result) => {
        if(err) return res.redirect('/')
        if(result.length !=1) return res.redirect('/')
        res.render('./article/edit.ejs',{
            user:req.session.user,
            islogin:req.session.islogin,
            article:result[0]
        })
    })

}

const aditArticle = (req,res) => {
    const body = req.body
    const sql = 'update hm_article set ? where id = ?'
    conn.query(sql,[body,body.id],(err,result)=> {
        if(err) return res.redirect('/')
        if(result.affectedRows!==1) return res.send({msg:'修改文章失败',status:'502'})
        res.send({msg:'修改文章成功',status:200})
    })
}


module.exports = {
    addArticlepage,
    addNewArticle,
    showArticle,
    editArticlePage,
    aditArticle
}